<?php

class wx {

    /**
     * 
     * @param type $appId
     * @param type $appSecret
     * @param type $sure 是否需要用户确认授权
     * @return type
     */
    public function getOpenId($appId, $appSecret, $sure = '') {

        $type = empty($sure) ? 'snsapi_base' : 'snsapi_userinfo';
        $url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        //get code
        if (!isset($_GET['code'])) {
            redirect('https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appId . '&redirect_uri=' . urlencode($url) . '&response_type=code&scope=' . $type . '&state=123#wechat_redirect');
            exit;
        }

        //get openid
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $appId . "&secret=" . $appSecret . "&code=" . $_GET['code'] . "&grant_type=authorization_code";
        $content = file_get_contents($url);
        $ret = json_decode($content, true);

        if (!isset($ret['openid'])) {
            echo 'get openID is fail';
            exit;
        }
        return $ret['openid'];
    }

}
